<?php

namespace App\Admin\Controllers;

use App\Models\JuniorTeamLeader;
use App\Models\SeniorTeamLeader;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Controllers\AdminController;

class JuniorTeamLeaderController extends AdminController
{
    protected $title = '初级团队长';

    protected function grid()
    {
        $grid = new Grid(new JuniorTeamLeader());

        $grid->column('id', 'ID');
        $grid->column('user_id', '会员')->display(function () {
            return $this->user->nameText(true) ;
        });
        
        
        $grid->disableExport();
        $grid->disableRowSelector();
        
        $this->gridActions($grid);

        return $grid;
    }
    
    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableView();
	    });
    }
    
    protected function form()
    {
        $form = new Form(new JuniorTeamLeader());

        $form->select('user_id', '会员')->options(User::all()->pluck('id', 'id'))
            ->rules('required');

  

        $this->formTools($form);
        $this->formFooter($form);
        $this->formSaving($form);

        return $form;
    }
    
    protected function formTools(Form $form)
    {
    	$form->tools(function (Form\Tools $tools) {
		    $tools->disableView();
	    });
    }
    
    protected function formFooter(Form $form)
    {
	    $form->footer(function (Form\Footer $footer) {
		    $footer->disableViewCheck();
		    $footer->disableCreatingCheck();
		    $footer->disableEditingCheck();
	    });
    }

     protected function formSaving(Form $form)
    {
        $form->saving(function (Form $form) {
            // Passowrd for editing mode
           $leader = JuniorTeamLeader::query()->where("user_id",$form->user_id)->first();
           if($leader){

                admin_toastr('不可重复添加', 'error');
                return redirect('/admin/junior-team-leaders');
           }

            $otherleader = SeniorTeamLeader::query()->where("user_id",$form->user_id)->first();
            if($otherleader){

                admin_toastr('已在高级团长行列', 'error');
                return redirect('/admin/junior-team-leaders');
           }
        });
    }

}
